package com.easymall.web;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet(name = "ProdImgServlet")
public class ProdImgServlet extends HttpServlet {

    private String uploadPath = "WEB-INF/upload";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String img = request.getParameter("img");
        if (null == img || "".equals(img) || img.length() != 32) {
            return;
        }

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(this.getServletContext().getRealPath(uploadPath));
        for (int i = 0; i < 8; i++) {
            stringBuilder.append("/");
            stringBuilder.append(img.charAt(i));
        }
        stringBuilder.append("/");
        stringBuilder.append(img);
        String filePath = stringBuilder.toString();
        File file = new File(filePath);
        if (!file.exists()) {
            return;
        }
        ServletOutputStream outputStream = response.getOutputStream();
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] buf = new byte[4096];
        int len = fileInputStream.read(buf);
        while (-1 != len) {
            outputStream.write(buf, 0, len);
            len =fileInputStream.read(buf);
        }
        fileInputStream.close();
    }
}
